package com.xique.door.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.enums.StatusCode;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.door.bean.domain.BaseUserV1;
import com.xique.door.bean.domain.UserV1;
import com.xique.door.bean.domain.WxMessageSendResult;
import com.xique.door.bean.domain.WxMessageTemplate;
import com.xique.door.bean.dto.OpenDoorTemplateDTO;
import com.xique.door.bean.request.wxMessage.WxDoorOpenMessageSendRequest;
import com.xique.door.bean.search.WxMessageTemplateListSearch;
import com.xique.door.biz.service.IWxMessageSendBizService;
import com.xique.door.constant.WxMessageTemplateConstants;
import com.xique.door.service.IBaseUserService;
import com.xique.door.service.IUserService;
import com.xique.door.service.IWxMessageSendResultService;
import com.xique.door.service.IWxMessageTemplateService;
import com.xique.door.util.WechatUtils;
import com.xique.system.api.RemoteSystemProjectService;
import com.xique.system.api.dto.SystemProjectDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shd
 * @create 2022/4/27 10:26
 */
@Service
@EnableAsync
@Slf4j
public class WxMessageSendBizServiceImpl implements IWxMessageSendBizService {

    @Value("${wx.gzh.appId}")
    private String appId;

    @Value("${wx.gzh.secret}")
    private String secret;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBaseUserService baseUserService;

    @Autowired
    private RemoteSystemProjectService projectService;

    @Autowired
    private WechatUtils wechatUtils;

    @Autowired
    private IWxMessageTemplateService wxMessageTemplateService;

    @Autowired
    private IWxMessageSendResultService wxMessageSendResultService;

    @Override
    @Async
    public void sendDoorOpenMessage(WxDoorOpenMessageSendRequest request) {

        UserV1 user = userService.getById(request.getUserId());
        log.info("【微信公众号推送】用户详细信息：{}", user);
        Long baseUserId = user.getBaseUserId();
        if (StringUtils.isNull(baseUserId)) {
            return;
        }

        BaseUserV1 baseUser = baseUserService.getById(baseUserId);
        log.info("【微信公众号推送】用户基础信息：{}", baseUser);
        String openId = baseUser.getWechatGzOpenid();

        if (StringUtils.isEmpty(openId)) {
            return;
        }

        WxMessageTemplateListSearch search = new WxMessageTemplateListSearch();
        search.setType(WxMessageTemplateConstants.Type.DOOR_OPEN_TEMPLATE);
        search.setStatus(Constants.NORMAL);
        List<WxMessageTemplate> list = wxMessageTemplateService.selectTemplateList(search);
        log.info("【微信公众号推送】推送模板：{}", list);
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        WxMessageTemplate template = list.get(0);
        String templateId = template.getTemplateId();

        Long parkId = user.getParkId();
        SystemProjectDTO project = projectService.getProjectInfo(parkId).getData();
        log.info("【微信公众号推送】项目信息：{}", project);

        OpenDoorTemplateDTO dto = new OpenDoorTemplateDTO();
        Map<String, Object> first = new HashMap<>(2);
        first.put("value", template.getFirst());
        first.put("color", template.getFirstColor());
        dto.setFirst(first);
        dto.setKeyword1(Collections.singletonMap("value", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, request.getIdentityTime())));
        dto.setKeyword2(Collections.singletonMap("value", baseUser.getUserName()));
        dto.setKeyword3(Collections.singletonMap("value", project.getName() + " " + request.getDeviceName()));
        Map<String, Object> remark = new HashMap<>(2);
        remark.put("value", template.getRemark());
        remark.put("color", template.getRemarkColor());
        dto.setRemark(remark);

        Map<String, Object> miniprogram = new HashMap<>(2);
        miniprogram.put("appid", template.getMiniAppId());
        miniprogram.put("pagepath", template.getPagepath());

        String url = template.getUrl();
        if (WxMessageTemplateConstants.JumpType.NONE == template.getJumpType()) {
            url = null;
            miniprogram = null;
        }
        if (WxMessageTemplateConstants.JumpType.URL == template.getJumpType()) {
            miniprogram = null;
        }
        if (WxMessageTemplateConstants.JumpType.MINIPROGRAM == template.getJumpType()) {
            url = null;
        }
        log.info("【微信公众号推送】推送参数：appid:{}, openid:{}, templateId:{}, url:{}, miniprogram:{}, dto:{}", appId, openId, templateId, url, miniprogram, dto);

        AjaxResult result = wechatUtils.sendMessage(appId, secret, openId, templateId, url, miniprogram, JSONObject.parseObject(JSONObject.toJSONString(dto)));

        // 记录推送结果
        WxMessageSendResult sendResult = new WxMessageSendResult();
        sendResult.setAppId(appId);
        sendResult.setOpenId(openId);
        sendResult.setTemplateId(template.getId());
        sendResult.setBaseUserId(baseUserId);
        sendResult.setResult(result.get(AjaxResult.MSG_TAG).toString());
        wxMessageSendResultService.save(sendResult);
        log.info("【微信公众号推送】推送结果：{}", sendResult);
    }
}
